<template>
  <div class="create-order-container">
    <el-steps :active="activeStep" finish-status="success" simple>
      <el-step title="选择车辆" />
      <el-step title="填写订单信息" />
      <el-step title="确认支付" />
      <el-step title="完成" />
    </el-steps>

    <!-- 步骤1：选择车辆 -->
    <div v-if="activeStep === 0" class="step-container">
      <el-card v-if="vehicle" class="vehicle-info">
        <div class="vehicle-image">
          <img :src="getImageUrl(vehicle.imageUrl)" alt="车辆图片" @error="handleImageError">
        </div>
        <div class="vehicle-details">
          <h2>{{ vehicle.brand }} {{ vehicle.model }}</h2>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="车牌号">{{ vehicle.plateNumber }}</el-descriptions-item>
            <el-descriptions-item label="颜色">{{ vehicle.color }}</el-descriptions-item>
            <el-descriptions-item label="座位数">{{ vehicle.seatCount }}</el-descriptions-item>
            <el-descriptions-item label="日租价格">¥ {{ vehicle.dailyPrice }}</el-descriptions-item>
          </el-descriptions>
          <div class="action-buttons">
            <el-button type="primary" @click="nextStep">选择该车辆</el-button>
            <el-button @click="goBack">返回</el-button>
          </div>
        </div>
      </el-card>
      <el-empty v-else description="车辆信息加载中..."></el-empty>
    </div>

    <!-- 步骤2：填写订单信息 -->
    <div v-if="activeStep === 1" class="step-container">
      <el-card>
        <h2>填写租车信息</h2>
        <el-form :model="orderForm" :rules="rules" ref="orderFormRef" label-width="120px">
          <el-form-item label="取车车行" prop="startShopId">
            <el-select v-model="orderForm.startShopId" placeholder="请选择取车车行">
              <el-option
                v-for="shop in shopList"
                :key="shop.id"
                :label="shop.shopName"
                :value="shop.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="还车车行" prop="endShopId">
            <el-select v-model="orderForm.endShopId" placeholder="请选择还车车行">
              <el-option
                v-for="shop in shopList"
                :key="shop.id"
                :label="shop.shopName"
                :value="shop.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="租车时间" prop="dateRange">
            <el-date-picker
              v-model="orderForm.dateRange"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              value-format="YYYY-MM-DD HH:mm:ss"
              @change="calculatePrice"
            />
          </el-form-item>
          <el-form-item label="预估费用">
            <span class="total-price">¥ {{ totalPrice }}</span>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitOrderForm">提交</el-button>
            <el-button @click="prevStep">上一步</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>

    <!-- 步骤3：确认支付 -->
    <div v-if="activeStep === 2" class="step-container">
      <el-card>
        <h2>确认并支付</h2>
        <el-descriptions title="订单信息" :column="1" border>
          <el-descriptions-item label="车辆">{{ vehicle.brand }} {{ vehicle.model }}</el-descriptions-item>
          <el-descriptions-item label="车牌号">{{ vehicle.plateNumber }}</el-descriptions-item>
          <el-descriptions-item label="取车车行">{{ getShopName(orderForm.startShopId) }}</el-descriptions-item>
          <el-descriptions-item label="还车车行">{{ getShopName(orderForm.endShopId) }}</el-descriptions-item>
          <el-descriptions-item label="租车时间">{{ orderForm.dateRange[0] }} 至 {{ orderForm.dateRange[1] }}</el-descriptions-item>
          <el-descriptions-item label="总价">
            <span class="total-price">¥ {{ totalPrice }}</span>
          </el-descriptions-item>
        </el-descriptions>
        
        <div class="payment-methods">
          <h3>支付方式</h3>
          <el-radio-group v-model="paymentMethod">
            <el-radio label="wechat">微信支付</el-radio>
            <el-radio label="alipay">支付宝</el-radio>
            <el-radio label="card">银行卡</el-radio>
          </el-radio-group>
        </div>
        
        <div class="action-buttons">
          <el-button type="primary" @click="payOrder">确认支付</el-button>
          <el-button @click="prevStep">上一步</el-button>
        </div>
      </el-card>
    </div>

    <!-- 步骤4：完成 -->
    <div v-if="activeStep === 3" class="step-container">
      <el-result
        icon="success"
        title="订单创建成功"
        sub-title="您的订单已创建成功，请按时取车"
      >
        <template #extra>
          <el-button type="primary" @click="goToOrderList">查看我的订单</el-button>
          <el-button @click="goToHome">返回首页</el-button>
        </template>
      </el-result>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { getVehicleDetail } from '@/api/vehicle'
import { createOrder } from '@/api/order'

const route = useRoute()
const router = useRouter()
const activeStep = ref(0)
const vehicle = ref(null)
const shopList = ref([
  { id: 1, shopName: '北京朝阳店' },
  { id: 2, shopName: '北京海淀店' },
  { id: 3, shopName: '上海静安店' },
  { id: 4, shopName: '上海浦东店' }
])
const paymentMethod = ref('wechat')
const orderFormRef = ref(null)
const totalPrice = ref(0)

// 订单表单
const orderForm = reactive({
  userId: Number(localStorage.getItem('userId') || 0),
  vehicleId: Number(route.params.id || 0),
  startShopId: '',
  endShopId: '',
  dateRange: []
})

// 表单验证规则
const rules = {
  startShopId: [
    { required: true, message: '请选择取车车行', trigger: 'change' }
  ],
  endShopId: [
    { required: true, message: '请选择还车车行', trigger: 'change' }
  ],
  dateRange: [
    { required: true, message: '请选择租车时间', trigger: 'change' }
  ]
}

// 计算租车价格
const calculatePrice = () => {
  if (!vehicle.value || !orderForm.dateRange || orderForm.dateRange.length < 2) {
    totalPrice.value = 0
    return
  }
  
  const startTime = new Date(orderForm.dateRange[0])
  const endTime = new Date(orderForm.dateRange[1])
  const days = Math.ceil((endTime - startTime) / (1000 * 60 * 60 * 24))
  
  // 至少一天
  const rentalDays = Math.max(1, days)
  totalPrice.value = (vehicle.value.dailyPrice * rentalDays).toFixed(2)
}

// 获取车行名称
const getShopName = (shopId) => {
  const shop = shopList.value.find(s => s.id === shopId)
  return shop ? shop.shopName : '未知车行'
}

// 获取车辆详情
const getVehicle = async () => {
  try {
    const vehicleId = route.params.id
    if (!vehicleId) {
      ElMessage.error('无效的车辆ID')
      router.push('/vehicle/list')
      return
    }
    
    const res = await getVehicleDetail(vehicleId)
    vehicle.value = res.data
  } catch (error) {
    console.error('获取车辆详情失败:', error)
    ElMessage.error('获取车辆详情失败')
  }
}

// 下一步
const nextStep = () => {
  activeStep.value++
}

// 上一步
const prevStep = () => {
  activeStep.value--
}

// 返回
const goBack = () => {
  router.push('/vehicle/list')
}

// 提交订单表单
const submitOrderForm = () => {
  orderFormRef.value.validate((valid) => {
    if (valid) {
      nextStep()
    }
  })
}

// 支付订单
const payOrder = async () => {
  try {
    // 创建订单
    const orderData = {
      userId: orderForm.userId,
      vehicleId: orderForm.vehicleId,
      startShopId: orderForm.startShopId,
      endShopId: orderForm.endShopId,
      startTime: orderForm.dateRange[0],
      endTime: orderForm.dateRange[1]
    }
    
    const res = await createOrder(orderData)
    ElMessage.success('订单创建成功')
    nextStep()
  } catch (error) {
    console.error('创建订单失败:', error)
    ElMessage.error('创建订单失败')
  }
}

// 查看订单列表
const goToOrderList = () => {
  router.push('/order/list')
}

// 返回首页
const goToHome = () => {
  router.push('/')
}

// 图片URL处理函数
const getImageUrl = (url) => {
  if (!url) return '/assets/no-image.png';
  
  // 如果是绝对URL（以http开头），直接返回
  if (url.startsWith('http://') || url.startsWith('https://')) {
    // 如果是placeholder站点且有连接问题，使用本地占位图
    if (url.includes('via.placeholder.com')) {
      return '/assets/no-image.png';
    }
    return url;
  }
  
  // 如果是相对URL，需要检查格式并调整
  
  // 1. 修正端口问题：从3000改为8081
  if (url.includes('localhost:3000')) {
    url = url.replace('localhost:3000', 'localhost:8081');
  }
  
  // 2. 如果URL不以/开头，添加/
  if (!url.startsWith('/')) {
    url = '/' + url;
  }
  
  // 拼接服务器地址，使用正确的端口8081
  const host = window.location.protocol + '//' + window.location.hostname + ':8081';
  return host + url;
}

// 图片加载错误处理
const handleImageError = (e) => {
  if (e && e.target) {
    // 使用本地资源文件夹中的占位图
    e.target.src = '/assets/no-image.png';
  }
}

// 组件挂载时获取车辆信息
onMounted(() => {
  getVehicle()
})
</script>

<style scoped>
.create-order-container {
  padding: 20px;
}

.step-container {
  margin-top: 30px;
}

.vehicle-info {
  display: flex;
  gap: 20px;
}

.vehicle-image {
  flex: 1;
  max-width: 500px;
}

.vehicle-image img {
  width: 100%;
  height: auto;
}

.vehicle-details {
  flex: 1;
}

.total-price {
  color: #f56c6c;
  font-size: 20px;
  font-weight: bold;
}

.action-buttons {
  margin-top: 20px;
}

.payment-methods {
  margin: 20px 0;
}
</style> 